//
//  YHRefreshControl.swift
//  YHWeibo
//
//  Created by 昱含 on 16/5/27.
//  Copyright © 2016年 YuHan. All rights reserved.
//

import UIKit
import SnapKit

private let refreshViewHeight: CGFloat = 60
enum refreshState: Int {
    case Normal
    case PullingDown
    case Refreshing
}

class YHRefreshControl: UIControl {
    
    var stated: refreshState = .Normal{
        didSet{
            switch stated {
            case .Normal:
            print("下拉起飞")
            arrowicon.hidden = false
            indicatorView.stopAnimating()
            tipLabel.text = "下拉起飞"
                UIView.animateWithDuration(0.25, animations: { 
                    self.arrowicon.transform = CGAffineTransformIdentity
                })
                
            if oldValue == .Refreshing {
                UIView.animateWithDuration(0.25, animations: { 
                    var inset = self.scrollView!.contentInset
                    inset.top -= refreshViewHeight
                    self.scrollView?.contentInset = inset
                })
            }
            
            case .PullingDown:
                print("准备起飞")
                tipLabel.text = "准备起飞"
                UIView.animateWithDuration(0.25, animations: {
                    self.arrowicon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                print("正在起飞")
                tipLabel.text = "正在起飞"
                //隐藏箭头
                arrowicon.hidden = true
                //转动小菊花
                indicatorView.startAnimating()
                
                sendActionsForControlEvents(.ValueChanged)
                
                UIView.animateWithDuration(0.25, animations: {
                    var inset = self.scrollView!.contentInset
                    inset.top += refreshViewHeight
                    self.scrollView?.contentInset = inset
                })

            }
        }
    }
    
    func endRefreshing() {
        let time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC)*0.6))
        dispatch_after(time_t, dispatch_get_main_queue()) { 
             self.stated = .Normal
        }
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>){
        
        let offSetY = scrollView?.contentOffset.y ?? 0
        
        if scrollView!.dragging {
            if stated == .PullingDown &&  offSetY > -124 {
                stated = .Normal
            }else if stated == .Normal && offSetY < -124 {
                stated = .PullingDown
            }
        }else{
            if stated == .PullingDown {
                stated = .Refreshing
            }
        }
        
    }
    
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshViewHeight, width: screenWidth, height: refreshViewHeight)
        super.init(frame: rect)
//        backgroundColor = UIColor.yellowColor()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(arrowicon)
        addSubview(tipLabel)
        addSubview(indicatorView)
        addSubview(backgroundImageView)
        arrowicon.snp_makeConstraints { (make) in
            make.centerY.equalTo(self.snp_centerY)
            make.centerX.equalTo(self.snp_centerX).offset(-30)
        }
        
        tipLabel.snp_makeConstraints { (make) in
            make.left.equalTo(arrowicon.snp_right)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        indicatorView.snp_makeConstraints { (make) in
            make.center.equalTo(arrowicon.snp_center)
        }
        
        backgroundImageView.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self)
        }
        
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        if let father = newSuperview as? UIScrollView {
            scrollView = father
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
        
    }
    
    
    private lazy var backgroundImageView: UIImageView = UIImageView(image: UIImage(named: "refreshbg"))
    private lazy var arrowicon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var  tipLabel: UILabel = UILabel(title: "下拉起飞", font: 14, textColor: UIColor.darkGrayColor())
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    var scrollView: UIScrollView?
    
    deinit{
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }


}
